import { CustomError } from '../../../services/auth-inteceptor';
import {
    Admin,
    Building,
    Company,
    Floor,
    Location,
    Project,
    SearchRet
} from '../../../shared/model/defination';
import { Component, OnInit } from '@angular/core';
import { Helper } from '../../common/index';
import { ControlBase } from '../../../shared/dynamicform/controlbase';
import { TextBox } from '../../../shared/dynamicform/textbox-control';
import { SelectBox } from '../../../shared/dynamicform/selectbox-control';
import {
    EmailValidator,
    PhoneValidator
} from '../../../shared/dynamicform/my-validator';
import { FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
import { Router, ActivatedRoute, Params, Route } from '@angular/router';
import { FloorService } from '../../../services/floor-service';
import { CompanyRequest, CompanyLocation } from '../../../dtos/CompanyRequest';
// import { Company, Floor, Location, Project, Building } from '../../../entities/entities';
import { MdlSnackbarService } from '@angular-mdl/core';
import { CompanyService } from '../../../services/company-service';
import { ProjectService } from '../../../services/project-service';
import { BuildingService } from '../../../services/building-service';
import { SessionService, SessionUser } from '../../../services/session-service';
import { UserService } from '../../../services/user-service';
import * as _ from 'lodash';

@Component({
    selector: 'company-edit',
    templateUrl: './edit.component.html',
    styleUrls: ['./edit.component.scss'],
    providers: [
        FloorService,
        CompanyService,
        ProjectService,
        BuildingService,
        SessionService,
        UserService
    ]
})
export class EditComponent implements OnInit {
    public locationProperties: Array<Location> = [];
    public isPosting: boolean = false;
    public get IsEdit() {
        return this._route.snapshot.params['id'] !== undefined;
    }

    private _editItem: Company;
    public isFormPosting: boolean = false;
    public locationConfigs: any;
    public projectConfigs: Array<any>;
    public floorConfigs: any;
    public selectedProject: number = -1;
    public selectedFloor: number = -1;
    public selectedBuilding: number;
    public userRole: string;
    formInputs: ControlBase<any>[];
    formControls: any;
    companyName: any = '';
    get IsLocationValid() {
        if (!this.locationProperties || this.locationProperties.length === 0) {
            return false;
        }
        const locationDataValid = l => {
            return l.project.id && l.building.id && l.floor.id && l.unit.id;
        };

        return this.locationProperties.filter(locationDataValid).length > 0;
    }
    constructor(
        private _floorService: FloorService,
        private _route: ActivatedRoute,
        private _router: Router,
        private _companyService: CompanyService,
        private _mdlSnackbarService: MdlSnackbarService,
        private _projectService: ProjectService,
        private _buildingService: BuildingService,
        private _userService: UserService,
        private _sessionService: SessionService
    ) {}

    async ngOnInit() {
        try {
            this.isPosting = true;

            const companyId = this.IsEdit
                ? +this._route.snapshot.params['id']
                : 0;
            if (companyId) {
                this._editItem = await this._companyService
                    .Get(companyId)
                    .toPromise();
                this.locationProperties = this._editItem.locations;
                if (
                    this._editItem.locations &&
                    this._editItem.locations.length &&
                    this._editItem.locations[0].project &&
                    this._editItem.locations[0].building &&
                    this._editItem.locations[0].floor
                ) {
                    this.selectedProject = this._editItem.locations[0].project.id;
                    this.selectedBuilding = this._editItem.locations[0].building.id;
                    this.selectedFloor = this._editItem.locations[0].floor.id;
                }
            }
            this.userRole = this._sessionService.getRoles()[0];
            if (this.userRole === '物业') {
                const session: Admin = await this._sessionService.getCurrentUser();
                const sessionUser = await this._userService
                    .Get(session.id)
                    .toPromise();
                this.selectedProject =
                    sessionUser.company.locations[0].project.id;
            }

            this.formControls = this._setForm(this._editItem);
        } catch (e) {
            console.log(e);
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
            this.isPosting = false;
        }
    }

    private _setForm(data: any): any {
        this.formInputs = [
            new TextBox({
                type: 'text',
                key: 'companyName',
                label: '公司名称',
                value: data ? data.name : '',
                required: true,
                order: 0,
                groupId: 1,
                validators: Validators.required
            }),
            new TextBox({
                type: 'text',
                key: 'telephone',
                label: '电话',
                value: data ? data.phone : '',
                required: true,
                order: 1,
                groupId: 2,
                require: true,
                validators: [Validators.required, PhoneValidator()]
            })
        ];
        return Helper.setGroupForm(this.formInputs);
    }
    async save(df: any) {
        console.log(this.locationProperties);
        const form = <FormGroup>df.form;
        if (!form.valid) {
            return false;
        }
        if (!this.IsLocationValid) {
            this._mdlSnackbarService.showToast('请添加位置信息', 1500);
            return false;
        }
        const request: CompanyRequest = {
            name: form.value.companyName,
            phone: form.value.telephone,
            locationIds: this.locationProperties.map(lp => lp.id)
        };
        let action$;
        if (this.IsEdit) {
            request.id = this._editItem.id;
        }
        action$ = !this.IsEdit
            ? this._companyService.Create(request)
            : this._companyService.Update(request);
        try {
            this.isFormPosting = true;
            const resp = await action$.toPromise();
            if (resp) {
                this._mdlSnackbarService.showToast('保存成功！', 2000);
                this._router.navigate(['/company']);
            }
        } catch (e) {
            if (e instanceof CustomError) {
                const msg = Object.keys(e.msg)
                    .map(k => e.msg[k][0])
                    .join(',');

                if (e.errCode == '1002') {
                    this._mdlSnackbarService.showToast('此单元以被使用，请更换公司位置', 2000);
                } else {
                    this._mdlSnackbarService.showToast(msg, 2000);
                }
            } else {
                this._mdlSnackbarService.showToast('此单元以被使用，请更换公司位置', 2000);
            }
        } finally {
            this.isFormPosting = false;
        }
    }
    public onLoadFormData(form) {
        this.companyName = form.companyName;
        // // 响应project select
        // let projectId = form.projectId;
        // let building: SelectBox = <SelectBox>this.formInputs.find(f => f.key === 'buildingId')
        // building.options = this.locationConfigs[projectId];
        // // 响应building select
        // let buildingId = form.buildingId;
        // let floor: SelectBox = <SelectBox>this.formInputs.find(f => f.key === 'floorId');
        // floor.options = this.floorConfigs[buildingId];
    }
}
